import { Ref, watch } from "vue";
import DomUtil from "../dom";
const { on, off, findTargetParent } = DomUtil;
/**
 * 当目标区域显示后，点击指定区域不隐藏，点击页面其它区域则隐藏
 * @param show 控制目标区域显示的属性
 * @param rootEl 指定区域的根节点，若不传则点击页面任意地方都隐藏
 */
export default function (show: Ref<boolean>, rootEl?: HTMLElement) {
  const listener = function (e: Event) {
    if (rootEl) {
      const result = findTargetParent(
        e.target as HTMLElement,
        (node: HTMLElement) => node === rootEl
      );
      if (!result) {
        show.value = false;
      }
    } else {
      show.value = false;
    }
  };
  watch(show, (val) => {
    if (val) {
      //这里要用mousedown 不用click 否则当在指定区域按下鼠标，然后移出指定区域放开鼠标，也会触发隐藏
      on(window, "mousedown", listener);
    } else {
      off(window, "mousedown", listener);
    }
  });
}
